package com.doctracker.controller;

import com.doctracker.model.Person;
import com.doctracker.service.FileRenameService;
import com.doctracker.service.TemplateManager;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.net.URL;
import java.util.*;
import java.util.List;

/**
 * 文件改名设置对话框控制器
 */
public class RenameDialogController implements Initializable {
    
    @FXML private FlowPane fieldsFlowPane;
    @FXML private HBox ruleElementsBox;
    @FXML private VBox previewBox;
    @FXML private Button addTextButton;
    @FXML private Button clearAllButton;
    @FXML private Button confirmButton;
    @FXML private Button cancelButton;
    @FXML private ComboBox<String> templateComboBox;
    @FXML private Button saveTemplateButton;
    
    private Set<String> availableFields;
    private List<Person> submittedPeople;
    private FileRenameService fileRenameService;
    private TemplateManager templateManager;
    private List<FileRenameService.RuleElement> currentRuleElements;
    private List<TemplateManager.TemplateItem> templateHistory;
    private boolean confirmed = false;
    
    // 回调接口
    public interface RenameConfirmCallback {
        void onConfirm(List<FileRenameService.RuleElement> ruleElements);
    }
    
    private RenameConfirmCallback callback;
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        currentRuleElements = new ArrayList<>();
        fileRenameService = new FileRenameService();
        templateManager = new TemplateManager();
        templateHistory = new ArrayList<>();
        
        // 初始化模板列表
        loadTemplateHistory();
        
        // 初始化样式
        initializeStyles();
    }
    
    /**
     * 设置数据和回调
     */
    public void setData(Set<String> availableFields, List<Person> submittedPeople, RenameConfirmCallback callback) {
        this.availableFields = availableFields;
        this.submittedPeople = submittedPeople;
        this.callback = callback;
        
        // 初始化界面
        Platform.runLater(() -> {
            initializeFieldButtons();
            updatePreview();
        });
    }
    
    /**
     * 初始化字段按钮
     */
    private void initializeFieldButtons() {
        fieldsFlowPane.getChildren().clear();
        
        for (String field : availableFields) {
            Button fieldButton = new Button("{" + field + "}");
            fieldButton.setStyle("-fx-background-color: #E3F2FD; -fx-text-fill: #1976D2; -fx-border-color: #1976D2; -fx-border-radius: 15; -fx-background-radius: 15;");
            fieldButton.setPrefHeight(30);
            fieldButton.setOnAction(e -> addFieldToRule(field));
            
            // 悬停效果
            fieldButton.setOnMouseEntered(e -> fieldButton.setStyle("-fx-background-color: #BBDEFB; -fx-text-fill: #1976D2; -fx-border-color: #1976D2; -fx-border-radius: 15; -fx-background-radius: 15;"));
            fieldButton.setOnMouseExited(e -> fieldButton.setStyle("-fx-background-color: #E3F2FD; -fx-text-fill: #1976D2; -fx-border-color: #1976D2; -fx-border-radius: 15; -fx-background-radius: 15;"));
            
            fieldsFlowPane.getChildren().add(fieldButton);
        }
    }
    
    /**
     * 加载模板历史
     */
    private void loadTemplateHistory() {
        templateHistory = templateManager.getTemplateHistory();
        
        ObservableList<String> templateItems = FXCollections.observableArrayList();
        templateItems.add("选择保存的模板...");
        
        for (TemplateManager.TemplateItem item : templateHistory) {
            templateItems.add(item.toString());
        }
        
        templateComboBox.setItems(templateItems);
        templateComboBox.getSelectionModel().selectFirst();
    }
    
    /**
     * 初始化样式
     */
    private void initializeStyles() {
        ruleElementsBox.setStyle("-fx-background-color: #F5F5F5; -fx-border-color: #E0E0E0; -fx-border-radius: 5; -fx-background-radius: 5;");
        ruleElementsBox.setPadding(new Insets(10));
        
        previewBox.setStyle("-fx-background-color: #FAFAFA; -fx-border-color: #E0E0E0; -fx-border-radius: 5; -fx-background-radius: 5;");
        previewBox.setPadding(new Insets(10));
    }
    
    /**
     * 添加字段到规则
     */
    private void addFieldToRule(String fieldName) {
        FileRenameService.RuleElement element = new FileRenameService.RuleElement("field", fieldName);
        currentRuleElements.add(element);
        updateRuleDisplay();
        updatePreview();
    }
    
    /**
     * 处理添加文本按钮
     */
    @FXML
    private void handleAddText() {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("添加文本");
        dialog.setHeaderText("输入要添加的固定文本");
        dialog.setContentText("文本内容:");
        
        Optional<String> result = dialog.showAndWait();
        if (result.isPresent() && !result.get().trim().isEmpty()) {
            FileRenameService.RuleElement element = new FileRenameService.RuleElement("text", result.get().trim());
            currentRuleElements.add(element);
            updateRuleDisplay();
            updatePreview();
        }
    }
    
    /**
     * 处理清空按钮
     */
    @FXML
    private void handleClearAll() {
        currentRuleElements.clear();
        updateRuleDisplay();
        updatePreview();
    }
    
    /**
     * 处理模板选择
     */
    @FXML
    private void handleTemplateSelect() {
        int selectedIndex = templateComboBox.getSelectionModel().getSelectedIndex();
        if (selectedIndex > 0 && selectedIndex <= templateHistory.size()) {
            TemplateManager.TemplateItem selectedTemplate = templateHistory.get(selectedIndex - 1);
            
            // 加载模板
            List<FileRenameService.RuleElement> templateElements = templateManager.loadTemplate(selectedTemplate.getFileName());
            
            // 验证模板中的字段是否都可用
            boolean isValid = true;
            List<String> missingFields = new ArrayList<>();
            for (FileRenameService.RuleElement element : templateElements) {
                if ("field".equals(element.getType()) && !availableFields.contains(element.getValue())) {
                    isValid = false;
                    missingFields.add(element.getValue());
                }
            }
            
            if (isValid) {
                currentRuleElements.clear();
                currentRuleElements.addAll(templateElements);
                updateRuleDisplay();
                updatePreview();
                System.out.println("已加载模板: " + selectedTemplate.getName());
            } else {
                String message = "该模板包含当前Excel中不存在的字段:\n" + String.join(", ", missingFields);
                showAlert("模板不可用", message);
                templateComboBox.getSelectionModel().selectFirst();
            }
        }
    }
    
    /**
     * 处理保存模板按钮
     */
    @FXML
    private void handleSaveTemplate() {
        if (currentRuleElements.isEmpty()) {
            showAlert("无规则可保存", "请先构建改名规则");
            return;
        }
        
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("保存模板");
        dialog.setHeaderText("保存当前改名规则为模板");
        dialog.setContentText("模板名称:");
        
        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()) {
            String templateName = result.get().trim();
            if (!templateName.isEmpty()) {
                boolean success = templateManager.saveTemplate(templateName, new ArrayList<>(currentRuleElements));
                if (success) {
                    // 重新加载模板列表
                    loadTemplateHistory();
                    showAlert("保存成功", "模板 \"" + templateName + "\" 已保存");
                } else {
                    showAlert("保存失败", "模板保存失败，请检查文件权限");
                }
            }
        }
    }
    
    /**
     * 更新规则显示
     */
    private void updateRuleDisplay() {
        ruleElementsBox.getChildren().clear();
        
        if (currentRuleElements.isEmpty()) {
            Label emptyLabel = new Label("点击上方字段按钮或添加文本来构建改名规则");
            emptyLabel.setStyle("-fx-text-fill: #9E9E9E; -fx-font-style: italic;");
            ruleElementsBox.getChildren().add(emptyLabel);
            return;
        }
        
        for (int i = 0; i < currentRuleElements.size(); i++) {
            FileRenameService.RuleElement element = currentRuleElements.get(i);
            
            // 创建元素显示
            VBox elementBox = createElementDisplay(element, i);
            ruleElementsBox.getChildren().add(elementBox);
            
            // 添加分隔符（除了最后一个元素）
            if (i < currentRuleElements.size() - 1) {
                Label separator = new Label("+");
                separator.setStyle("-fx-font-weight: bold; -fx-text-fill: #757575;");
                ruleElementsBox.getChildren().add(separator);
            }
        }
    }
    
    /**
     * 创建规则元素显示
     */
    private VBox createElementDisplay(FileRenameService.RuleElement element, int index) {
        VBox elementBox = new VBox(2);
        elementBox.setStyle("-fx-background-color: white; -fx-border-color: #E0E0E0; -fx-border-radius: 3; -fx-background-radius: 3; -fx-padding: 5;");
        
        // 元素内容
        Label contentLabel;
        if ("field".equals(element.getType())) {
            contentLabel = new Label("{" + element.getValue() + "}");
            contentLabel.setStyle("-fx-text-fill: #1976D2; -fx-font-weight: bold;");
        } else {
            contentLabel = new Label("\"" + element.getValue() + "\"");
            contentLabel.setStyle("-fx-text-fill: #388E3C;");
        }
        
        // 删除按钮
        Button deleteButton = new Button("×");
        deleteButton.setStyle("-fx-background-color: #F44336; -fx-text-fill: white; -fx-font-size: 10px; -fx-padding: 1 4 1 4;");
        deleteButton.setOnAction(e -> {
            currentRuleElements.remove(index);
            updateRuleDisplay();
            updatePreview();
        });
        
        HBox contentBox = new HBox(5);
        contentBox.getChildren().addAll(contentLabel, deleteButton);
        
        elementBox.getChildren().add(contentBox);
        return elementBox;
    }
    
    /**
     * 更新预览
     */
    private void updatePreview() {
        previewBox.getChildren().clear();
        
        if (currentRuleElements.isEmpty()) {
            Label emptyLabel = new Label("构建规则后将在此处显示预览效果");
            emptyLabel.setStyle("-fx-text-fill: #9E9E9E; -fx-font-style: italic;");
            previewBox.getChildren().add(emptyLabel);
            confirmButton.setDisable(true);
            return;
        }
        
        // 生成预览
        List<FileRenameService.RenameResult> previewResults = fileRenameService.previewRename(submittedPeople, currentRuleElements);
        
        if (previewResults.isEmpty()) {
            Label noFileLabel = new Label("没有找到需要改名的文件");
            noFileLabel.setStyle("-fx-text-fill: #FF5722;");
            previewBox.getChildren().add(noFileLabel);
            confirmButton.setDisable(true);
            return;
        }
        
        // 显示预览结果（最多显示5个）
        int maxShow = Math.min(previewResults.size(), 5);
        for (int i = 0; i < maxShow; i++) {
            FileRenameService.RenameResult result = previewResults.get(i);
            
            VBox resultBox = new VBox(2);
            resultBox.setStyle("-fx-background-color: #F9F9F9; -fx-border-color: #E0E0E0; -fx-border-radius: 3; -fx-background-radius: 3; -fx-padding: 8;");
            
            Label originalLabel = new Label("原文件: " + result.getOriginalName());
            originalLabel.setStyle("-fx-text-fill: #616161; -fx-font-size: 12px;");
            
            Label newLabel = new Label("新文件: " + result.getNewName());
            if (result.isSuccess()) {
                newLabel.setStyle("-fx-text-fill: #2E7D32; -fx-font-weight: bold; -fx-font-size: 12px;");
            } else {
                newLabel.setStyle("-fx-text-fill: #D32F2F; -fx-font-size: 12px;");
                Label errorLabel = new Label("⚠️ " + result.getErrorMessage());
                errorLabel.setStyle("-fx-text-fill: #FF5722; -fx-font-size: 11px;");
                resultBox.getChildren().add(errorLabel);
            }
            
            resultBox.getChildren().addAll(originalLabel, newLabel);
            previewBox.getChildren().add(resultBox);
        }
        
        if (previewResults.size() > maxShow) {
            Label moreLabel = new Label("...还有 " + (previewResults.size() - maxShow) + " 个文件");
            moreLabel.setStyle("-fx-text-fill: #757575; -fx-font-style: italic; -fx-font-size: 12px;");
            previewBox.getChildren().add(moreLabel);
        }
        
        // 检查是否有错误
        boolean hasErrors = previewResults.stream().anyMatch(r -> !r.isSuccess());
        confirmButton.setDisable(hasErrors);
        
        if (hasErrors) {
            Label warningLabel = new Label("⚠️ 存在无效的文件名，请修改规则");
            warningLabel.setStyle("-fx-text-fill: #FF5722; -fx-font-weight: bold; -fx-font-size: 12px;");
            previewBox.getChildren().add(0, warningLabel);
        }
    }
    
    /**
     * 处理确认按钮
     */
    @FXML
    private void handleConfirm() {
        if (currentRuleElements.isEmpty()) {
            showAlert("规则为空", "请先构建改名规则");
            return;
        }
        
        confirmed = true;
        if (callback != null) {
            callback.onConfirm(new ArrayList<>(currentRuleElements));
        }
        closeDialog();
    }
    
    /**
     * 处理取消按钮
     */
    @FXML
    private void handleCancel() {
        confirmed = false;
        closeDialog();
    }
    
    /**
     * 关闭对话框
     */
    private void closeDialog() {
        Stage stage = (Stage) cancelButton.getScene().getWindow();
        stage.close();
    }
    
    /**
     * 显示提示对话框
     */
    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
    
    /**
     * 是否已确认
     */
    public boolean isConfirmed() {
        return confirmed;
    }
} 